package com.ifast.asset.util;

import com.ifast.asset.domain.TaskrecordDO;
import com.ifast.asset.service.*;
import com.ifast.asset.service.impl.IpsegmentServiceImpl;
import com.ifast.asset.service.impl.TaskipServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Component
public class NmapExecuteUtil {

    @Autowired
    TaskipServiceImpl taskipServiceImpl;
    @Autowired
    TaskrecordService taskServiceImpl;
    @Autowired
    AssetUtil assetUtil;
    @Autowired
    IpsegmentServiceImpl ipsegmentServiceImpl;
    @Autowired
    AssetsService assetsService;
    @Autowired
    LabelassetService labelassetService;
    @Autowired
    LabelService labelService;
    @Autowired
    SegmentService segmentService;


    public boolean execute(TaskrecordDO task) {

        try {
            String comString = "ps -aux | grep nmap";
            List<String> numString = executeLinuxCmd(comString);
            while (numString.size() > 20) {

                Thread.sleep(1000);
                numString = executeLinuxCmd(comString);
            }
            ExecutorService executorService = NewThreadPool.getExecutorService();
            executorService.submit(new CommandThread(task.getIp(), task, taskipServiceImpl, taskServiceImpl, assetUtil,ipsegmentServiceImpl,
                    assetsService,labelassetService,labelService,segmentService));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public List<String> executeLinuxCmd(String cmd) {
        //System.out.println("got cmd job : " + cmd);
        Runtime run = Runtime.getRuntime();
        try {
//            Process process = run.exec(cmd);
            Process process = run.exec(new String[]{"/bin/sh", "-c", cmd});
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            List<String> list = new ArrayList<String>();
            String result = null;
            while ((result = bs.readLine()) != null) {
                System.out.println("job result [" + result + "]");
                list.add(result);
            }
            in.close();
            // process.waitFor();
            process.destroy();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
